package com.blue.integration.spring.amqp;

import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blue.core.util.CompressUtil;

public class FastJsonMessageConverter extends AbstractMessageConverter
{
	private static final String CHARSET = "UTF-8";

	private static SerializerFeature[] serializer = new SerializerFeature[] { SerializerFeature.WriteDateUseDateFormat,
			SerializerFeature.WriteClassName };

	private static Feature[] feature = new Feature[] {};

	private boolean compress = false; // 是否压缩

	static
	{
		ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
	}

	public FastJsonMessageConverter()
	{
	}

	public FastJsonMessageConverter(boolean compress)
	{
		this.compress = compress;
	}

	@Override
	protected Message createMessage(Object object, MessageProperties messageProperties)
	{
		byte[] bytes = JSON.toJSONBytes(object, serializer);
		if (compress) // 压缩
		{
			bytes = CompressUtil.zip(bytes);
		}
		
		messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
		messageProperties.setContentEncoding(CHARSET);
		if (bytes != null)
		{
			messageProperties.setContentLength(bytes.length);
		}
		return new Message(bytes, messageProperties);
	}

	@Override
	public Object fromMessage(Message message) throws MessageConversionException
	{
		byte[] bytes = message.getBody();
		if (compress)
		{
			bytes = CompressUtil.unzip(bytes);
		}
		
		Object obj = JSON.parse(bytes, feature);
		return obj;
	}

	public boolean isCompress()
	{
		return compress;
	}

	public void setCompress(boolean compress)
	{
		this.compress = compress;
	}

}
